package com.esun.payment_api.service.impl;

import com.esun.common.api.CommonResult;
import com.esun.payment_api.bean.*;
import com.esun.payment_api.dao.InvFormDao;
import com.esun.payment_api.domain.*;
import com.esun.payment_api.mapper.*;
import com.esun.payment_api.service.HomePageService;
import com.esun.payment_api.service.LogService;
import com.esun.payment_api.service.XcxInfoService;
import com.github.pagehelper.PageHelper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class HomePageServiceImpl implements HomePageService {
    @Resource
    HomePageMapper homePageMapper;

    @Resource
    SysMessageUserMapper sysMessageUserMapper;

    @Resource
    EsunFlowMapper esunFlowMapper;

    @Resource
    DkClaimMapper dkClaimMapper;

    @Resource
    DkClaimCancelMapper dkClaimCancelMapper;

    @Resource
    InvFormMapper invFormMapper;

    @Resource
    XcxInfoService xcxInfoService;

    @Resource
    LogService logService;
    final String moduleName = "首页";

    @Override
    public List<MyApplicationBean> getMyApplication(User user, Integer flowStatus, String searchStr, Integer pageSize, Integer pageNum) throws Exception{
        PageHelper.startPage(pageNum,pageSize);
        List<MyApplicationBean> list = homePageMapper.getMyApplication(user.getId(), user.getCoId(), flowStatus, searchStr, null);
        return list;
    }

    @Override
    public List<MyApplicationBean> getApplicationById(User user, Integer flowId) throws Exception{
        List<MyApplicationBean> list = homePageMapper.getMyApplication(user.getId(), user.getCoId(), null, null, flowId);
        return list;
    }

    @Override
    public List<MyExamineBean> getMyExamine(User user, String searchStr, String type, Integer pageSize, Integer pageNum) throws Exception{
        PageHelper.startPage(pageNum,pageSize);
        List<MyExamineBean> list = homePageMapper.getMyExamine(user.getId(), searchStr, null, type);
        return list;
    }

    @Override
    public List<MyExamineBean> getExamineById(User user, Integer flowId) throws Exception{
        List<MyExamineBean> list = homePageMapper.getMyExamine(user.getId(), null, flowId, null);
        return list;
    }

    @Override
    public List<MyExamineBean> getMyExamineHistory(User user, Integer flowStatus, String searchStr, Integer pageSize, Integer pageNum) throws Exception{
        PageHelper.startPage(pageNum,pageSize);
        List<MyExamineBean> list = homePageMapper.getMyExamineHistory(user.getId(), flowStatus, searchStr, null);
        return list;
    }

    //获取本部门已审批
    @Override
    public List<MyExamineBean> getMyDeptExamineHistory(User user, Integer flowStatus, String searchStr, Integer pageSize, Integer pageNum) throws Exception {
        PageHelper.startPage(pageNum,pageSize);
        List<MyExamineBean> list = homePageMapper.getMyDeptExamineHistory(user.getId(), user.getDeptId(), flowStatus, searchStr, null);
        return list;
    }

    @Override
    public List<MyExamineBean> getExamineHistoryById(User user, Integer flowId) throws Exception{
        List<MyExamineBean> list = homePageMapper.getMyExamineHistory(user.getId(), null, null, flowId);
        return list;
    }

    @Override
    public List<MyMessageBean> getMyMessage(User user, Boolean unreadOnly, String searchStr, Integer pageSize, Integer pageNum) throws Exception{
        PageHelper.startPage(pageNum,pageSize);
        List<MyMessageBean> list = homePageMapper.getMyMessage(user.getId(), unreadOnly, searchStr,null);
        return list;
    }

    @Override
    public List<MyMessageBean> getMessageById(User user, Integer messageId) throws Exception{
        List<MyMessageBean> list = homePageMapper.getMyMessage(user.getId(), null,null, messageId);
        return list;
    }

    @Override
    public List<MyToDoBean> getMyToDo(User user, Boolean unreadOnly, String searchStr, Integer pageSize, Integer pageNum) throws Exception{
        PageHelper.startPage(pageNum,pageSize);
        List<MyToDoBean> list = homePageMapper.getMyToDo(user.getId(), unreadOnly, searchStr,null);
        return list;
    }

    @Override
    public List<MyToDoBean> getToDoById(User user, Integer messageId) throws Exception{
        List<MyToDoBean> list = homePageMapper.getMyToDo(user.getId(), null, null, messageId);
        return list;
    }

    @Override
    public HomePageInfo getHomePageInfo(User user){
        HomePageInfo homePageInfo = new HomePageInfo();
        homePageInfo.setUserName(user.getUserName());


        List<MyMessageBean> list2 = homePageMapper.getMyMessage(user.getId(), null, null,null);
        homePageInfo.setMessageCount(list2.size());
        List<MyApplicationBean> list3 = homePageMapper.getMyApplication(user.getId(), user.getCoId(),null,null,null);
        homePageInfo.setApplicationCount(list3.size());
        List<MyExamineBean> list4 = homePageMapper.getMyExamine(user.getId(),null,null,null);
        homePageInfo.setExamineCount(list4.size());
//        List<MyToDoBean> list1 = homePageMapper.getMyToDo(user.getId(), null, null, null);
        homePageInfo.setToDoCount(list2.size()+list4.size());

        return homePageInfo;
    }

    @Override
    public CommonResult messageSetRead(User user, Short messageId){
        try{
            SysMessageUser sysMessageUser = new SysMessageUser();
            sysMessageUser.setReadFlag((short)1);
            Date date = new Date();
            sysMessageUser.setReadDate(date);

            SysMessageUserExample example = new SysMessageUserExample();
            SysMessageUserExample.Criteria criteria = example.createCriteria();
            criteria.andAcceptIdEqualTo(user.getId());
            criteria.andMsgIdEqualTo(messageId);
            criteria.andIsDeletedEqualTo("0");
            if (sysMessageUserMapper.updateByExampleSelective(sysMessageUser, example) < 1 ){
                return CommonResult.failed("未能设置已读");
            }
            return CommonResult.success(null,"消息已读设置完成");
        }catch (Exception e){
            return CommonResult.failed("消息已读设置失败，参考原因"+e.getMessage());
        }
    }

    @Override
    public CommonResult messageDelete(User user, Short messageId){
        try{
            SysMessageUser sysMessageUser = new SysMessageUser();
            sysMessageUser.setIsDeleted("1");
            Date date = new Date();
            sysMessageUser.setDeleteAt(date);
            sysMessageUser.setDeleteBy(user.getId());

            SysMessageUserExample example = new SysMessageUserExample();
            SysMessageUserExample.Criteria criteria = example.createCriteria();
            criteria.andAcceptIdEqualTo(user.getId());
            criteria.andMsgIdEqualTo(messageId);
            if (sysMessageUserMapper.updateByExampleSelective(sysMessageUser, example) < 1 ){
                return CommonResult.failed("未能删除消息");
            }
            return CommonResult.success(null,"消息删除完成");
        }catch (Exception e){
            return CommonResult.failed("消息删除设置失败，参考原因"+e.getMessage());
        }
    }

    public List<DkInvoiceBean> queryInvoice(User user, Integer flowStatus, String searchStr, Integer pageSize, Integer pageNum){
        PageHelper.startPage(pageNum,pageSize);
        List<DkInvoiceBean> list = homePageMapper.queryInvoice(user.getCoId(), flowStatus, searchStr);
        return list;
    }

    public List<DkReceiveBean> queryReceive(User user, String searchStr, Integer pageSize, Integer pageNum) {
        PageHelper.startPage(pageNum,pageSize);
        List<DkReceiveBean> list = homePageMapper.queryReceive(user.getCoId(), user.getDeptId(), searchStr);
        return list;
    }

    public CommonResult batchApprove(User user, String flowIdStr, String flowNotes){
        //拆分出每一条流程ID
        ArrayList<Integer> flowIdList = new ArrayList<>();
        try{
            String[] list = flowIdStr.split(",");
            for(String s : list){
                flowIdList.add(Integer.valueOf(s));
            }
        } catch (Exception e){
            return CommonResult.failed("输入的flowIdStr无法正常拆解为数组");
        }
        try{
            for(Integer flowId : flowIdList){
                //对于每一条流程判断一下该审批到底是哪一类
                EsunFlow esunFlow = esunFlowMapper.selectByPrimaryKey(flowId);
                //针对该类别调用函数
                handleFlow(esunFlow, flowNotes, user, true);

                xcxInfoService.sendWxMessage(flowId);
            }
        } catch (Exception e){
            e.printStackTrace();
            logService.writeErrorLog("批量通过审批失败，参考原因"+e.getMessage(),moduleName);
            return CommonResult.failed("批量通过审批失败");
        }
        CommonResult commonResult = CommonResult.success(null,"批量通过审批完成");
        logService.writeOperationLog(moduleName, commonResult);
        return commonResult;
    }

    public CommonResult batchDecline(User user, String flowIdStr, String flowNotes){
        //拆分出每一条流程ID
        ArrayList<Integer> flowIdList = new ArrayList<>();
        try{
            String[] list = flowIdStr.split(",");
            for(String s : list){
                flowIdList.add(Integer.valueOf(s));
            }
        } catch (Exception e){
            return CommonResult.failed("输入的flowIdStr无法正常拆解为数组");
        }
        try{
            for(Integer flowId : flowIdList){
                //对于每一条流程判断一下该审批到底是哪一类
                EsunFlow esunFlow = esunFlowMapper.selectByPrimaryKey(flowId);
                //针对该类别调用函数
                handleFlow(esunFlow, flowNotes, user, false);
            }
        } catch (Exception e){
            e.printStackTrace();
            logService.writeErrorLog("批量拒绝审批失败，参考原因"+e.getMessage(),moduleName);
            return CommonResult.failed("批量拒绝审批失败");
        }
        CommonResult commonResult = CommonResult.success(null,"批量拒绝审批完成");
        logService.writeOperationLog(moduleName, commonResult);
        return commonResult;
    }

    public void handleFlow(EsunFlow esunFlow, String flowNotes, User user, Boolean approved){
        if(esunFlow.getFlowTypeId()==41 || esunFlow.getFlowTypeId() == 161 || esunFlow.getFlowTypeId() == 201 || esunFlow.getFlowTypeId() == 221
                || esunFlow.getFlowTypeId() == 241 || esunFlow.getFlowTypeId() == 243 || esunFlow.getFlowTypeId() == 245 || esunFlow.getFlowTypeId() == 247
                || esunFlow.getFlowTypeId() == 261 || esunFlow.getFlowTypeId() == 321 || esunFlow.getFlowTypeId() == 401 || esunFlow.getFlowTypeId() == 403
                || esunFlow.getFlowTypeId() == 421 || esunFlow.getFlowTypeId() == 423){
            //发票审批
            if(approved){
                invFormMapper.invProcessApproval((short) 1, esunFlow.getId(), flowNotes, user.getId(), esunFlow.getFromId());
            } else {
                invFormMapper.invProcessApproval((short) -1, esunFlow.getId(), flowNotes, user.getId(), esunFlow.getFromId());
            }
        } else if(esunFlow.getFlowTypeId()==61 || esunFlow.getFlowTypeId() == 162 || esunFlow.getFlowTypeId() == 202 || esunFlow.getFlowTypeId() == 222
                || esunFlow.getFlowTypeId() == 242 || esunFlow.getFlowTypeId() == 244 || esunFlow.getFlowTypeId() == 246 || esunFlow.getFlowTypeId() == 248
                || esunFlow.getFlowTypeId() == 262 || esunFlow.getFlowTypeId() == 402 || esunFlow.getFlowTypeId() == 404 || esunFlow.getFlowTypeId() == 422
                || esunFlow.getFlowTypeId() == 424){
            //发票作废审批
            if(approved){
                invFormMapper.cancelInvProcessApproval((short) 1, esunFlow.getId(), flowNotes, user.getId(), esunFlow.getFromId());
            } else {
                invFormMapper.cancelInvProcessApproval((short) -1, esunFlow.getId(), flowNotes, user.getId(), esunFlow.getFromId());
            }
        } else if(esunFlow.getFlowTypeId()==81 || esunFlow.getFlowTypeId()==121 || esunFlow.getFlowTypeId()==141 || esunFlow.getFlowTypeId()==142
                || esunFlow.getFlowTypeId()== 181 || esunFlow.getFlowTypeId()== 301 || esunFlow.getFlowTypeId()== 341 || esunFlow.getFlowTypeId()== 361
                || esunFlow.getFlowTypeId()== 381 || esunFlow.getFlowTypeId()== 405 || esunFlow.getFlowTypeId()== 425 || esunFlow.getFlowTypeId()== 426){
            //到款认领审批
            if(approved){
                dkClaimMapper.approveClaim(esunFlow.getId(), esunFlow.getFromId(), flowNotes, user.getId());
            } else {
                dkClaimMapper.rejectClaim(esunFlow.getId(), esunFlow.getFromId(), flowNotes, user.getId());
            }
        } else if(esunFlow.getFlowTypeId()==101){
            //到款认领作废审批
            if(approved){
                dkClaimCancelMapper.approveClaimAbolish(esunFlow.getId(), flowNotes, user.getId(), esunFlow.getFromId());
            } else {
                dkClaimCancelMapper.rejectClaimAbolish(esunFlow.getId(), flowNotes, user.getId(), esunFlow.getFromId());
            }
        } else {
            System.out.println("未识别的流程类型，请更新HomePageServiceImpl中handleFlow方法");
            logService.writeErrorLog("未识别的流程类型，请更新HomePageServiceImpl中handleFlow方法", moduleName);
        }
    }

    public List<InvFormDao> getOverdueInvoice(User user, String searchStr, Integer pageSize, Integer pageNum){
        PageHelper.startPage(pageNum,pageSize);
        List<InvFormDao> list = homePageMapper.getOverdueInvoice(user.getCoId(), user.getId(), user.getDeptId(), searchStr);
        return list;
    }

    public List<UnfilledBean> getUnfilledList(User user, String searchStr, Integer pageSize, Integer pageNum){
        PageHelper.startPage(pageNum,pageSize);
        List<UnfilledBean> list = homePageMapper.getUnfilledList(user.getCoId(), user.getId(), user.getDeptId(), searchStr);
        return list;
    }


}
